package com.wctj.api.business.common.service.handler;

import com.wctj.api.business.common.dto.DdwxPaymentMessageInfoDTO;
import com.wctj.api.business.common.service.DdwxPaymentMessageInfoService;
import com.wctj.api.business.common.service.EventTypeResponse;
import com.wctj.api.infra.common.bean.NoticeParams;
import com.wctj.api.infra.common.bean.NoticeRequest;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;

/**
 * 汇付天下-Adapay-payment 支付回调响应模式处理
 */
@Slf4j
public abstract class HuiFuAbstractEventTypeResponse implements EventTypeResponse {

    @Resource
    protected DdwxPaymentMessageInfoService ddwxPaymentMessageInfoService;

    protected void updateMessage(String orderNo, int status,int pushStatus, LocalDateTime pushTime, String noticeBodyJsonStr) {
        DdwxPaymentMessageInfoDTO msgInfo = ddwxPaymentMessageInfoService.findByPayOrderNumber(orderNo);
        DdwxPaymentMessageInfoDTO ddwxPaymentMessageInfoDTO = new DdwxPaymentMessageInfoDTO(msgInfo.getId(), pushStatus, pushTime);
        ddwxPaymentMessageInfoDTO.setPushMsg(noticeBodyJsonStr);
        ddwxPaymentMessageInfoDTO.setStatus(status);
        ddwxPaymentMessageInfoService.updateById(ddwxPaymentMessageInfoDTO);
    }

    @Override
    public <P extends NoticeParams> P getNoticeParams(NoticeRequest request){
        // 获取请求地址后的的参数 eg: ${ur}?a=1&b=3
        final Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, Object> params = new TreeMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            StringBuilder sb = new StringBuilder();
            for (int i = 0, len = values.length; i < len; i++) {
                sb.append(values[i]).append((i == len - 1) ? "" : ',');
            }
            // 默认都是 UTF-8
            String valueStr = sb.toString();
            params.put(name, valueStr);
        }
        return (P) new NoticeParams(params);
    }
}
